import webapp2
import datetime
import sys
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext.webapp.util import run_wsgi_app
import os
import template

class ChatMessage(db.Model):
    timestamp = db.DateTimeProperty(auto_now_add = True)
    message = db.TextProperty(required = True)
    user = db.StringProperty(required = True)
    
    def __str__(self):
        return "%s (%s): %s\n" % (self.user, self.timestamp, self.message)

class ChatRoomPage(webapp2.RequestHandler):
    def get(self):
        user = users.get_current_user()
        if user is None:
            self.redirect(users.create_login_url(self.request.url))
        else:
            self.response.headers["Content-Type"] = "text/html"
            # output all message
            #messages = db.GqlQuery("SELECT * From ChatMessage ORDER BY timestamp")
            messages = ChatMessage.gql("ORDER BY timestamp")
            template_value = {
                    'title': "Wayne's room",
                    'msg_list': messages,
                    }
            path = os.path.join(os.path.dirname(__file__), 'chat-template.html')
            page = template.render(path, template_value)
            self.response.out.write(page)

    def post(self):
        user = users.get_current_user()
        if user is None:
            self.redirect(users.create_login_url(self.request.url))        
        user = users.get_current_user()
        msgtext = self.request.get("message")
        if user.nickname() is None or user.nickname() == "":
            nick = "No nickname"
        else:
            nick = user.nickname()
        msg = ChatMessage(user = user.nickname(), message = msgtext)
        msg.put()
        sys.stderr.write("****** Just stored message: %s" % msg)
        self.redirect("/")


chatapp = webapp2.WSGIApplication([("/", ChatRoomPage)])

def main():
    run_wsgi_app(chatapp)

if __name__ == "__main__":
    main()
